#include "StdAfx.h"
#include "stdio.h"
#include "stdlib.h"
#include "config.h"

ConfigFile::ConfigFile():m_pHost(NULL),m_pUsername(NULL),m_pPassword(NULL),m_port(3306),m_ver(0)
{
}
ConfigFile::ConfigFile(char* pFileName):m_pHost(NULL),m_pUsername(NULL),m_pPassword(NULL),m_port(3306),m_ver(0)
{
	SetFile(pFileName);
}
char* ConfigFile::GetHostName()
{
	return m_pHost;
}

char* ConfigFile::GetUserName()
{
	return m_pUsername;
}

char* ConfigFile::GetPassword()
{
	return m_pPassword;
}

int ConfigFile::GetVersion()
{
	return m_ver;
}

int ConfigFile::Parse()
{
	FILE* fp=fopen(m_pFileName,"rb");
	char pVer[8]={'\0'};
	fread(pVer,4,1,fp);
	int ver=0;
	memcpy(&ver,pVer,sizeof(int));
	m_ver=ver;
	char phostlen[8]={'\0'};
	fread(phostlen,4,1,fp);
	int hostlen=0;
	memcpy(&hostlen,phostlen,sizeof(int));
	char* pHostName=new char[hostlen+1];
	pHostName[hostlen]='\0';
	fread(pHostName,hostlen,1,fp);
	m_pHost=pHostName;

	char pusernamelen[8]={'\0'};
	fread(pusernamelen,4,1,fp);
	int usernamelen=0;
	memcpy(&usernamelen,pusernamelen,sizeof(int));
	char* pUserName=new char[usernamelen+1];
	pUserName[usernamelen]='\0';
	fread(pUserName,usernamelen,1,fp);
	m_pUsername=pUserName;

	char ppasswordlen[8]={'\0'};
	fread(ppasswordlen,4,1,fp);
	int pwdlen=0;
	memcpy(&pwdlen,ppasswordlen,sizeof(int));
	char* pPassword=new char[pwdlen+1];
	pPassword[pwdlen]='\0';
	fread(pPassword,pwdlen,1,fp);
	m_pPassword=pPassword;

	char pport[8]={'\0'};
	fread(pport,4,1,fp);
	int port=0;
	memcpy(&port,pport,sizeof(int));
	m_port=port;
	
	return 0;
}

int ConfigFile::SetFile(char* pFileName)
{
	int len=strlen(pFileName);
	char* pFile=new char[len+1];
	pFile[len]='\0';
	strcpy(pFile,pFileName);
	m_pFileName=pFile;
	return 0;
}
ConfigFile::~ConfigFile()
{
	if(m_pHost!=NULL)
		delete m_pHost;
	if(m_pUsername!=NULL)
		delete m_pUsername;
	if(m_pPassword!=NULL)
		delete m_pPassword;
}